package com.ruoyi.wlxz.tools;
import com.aliyun.bailian20231229.models.AddFileResponse;
import com.aliyun.bailian20231229.models.ApplyFileUploadLeaseResponse;
import com.aliyun.bailian20231229.models.ApplyFileUploadLeaseResponseBody;
import com.aliyun.tea.TeaException;
import com.ruoyi.wlxz.util.BaseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
@Service
public class FileManager {
    static String FileUploadLeaseId;//租约唯一 ID，后续调用 AddFile 接口时，需要使用该参数。
    static String FileUploadUrl;//文档的上传 URL 地址。
    static String fileId;//文档 ID，请妥善保管该值，它将用于后续与此文档相关的所有 API 操作
    static String ContentType;//需要放到 Header 中的 K-V 字段，K 和 V 均为字符串。
    static String Xbailianextra;
    static com.aliyun.bailian20231229.Client client;
    static String cate;//不同类目:政策,活动,将类目存入数据库
    @Autowired
    private BaseConfig config;
    /**
     * 新增文档
     *
     * @param categoryId
     * @param file
     * @return
     * @throws Exception
     */
    //申请文档上传租约
    public String ApplyFileUploadLease(String categoryId, MultipartFile file) throws Exception {
        client = config.createClient();
        cate = categoryId;
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest()
                .setMd5(DigestUtils.md5DigestAsHex(file.getInputStream()))
                .setFileName(file.getOriginalFilename())//获得文件名称
                .setSizeInBytes(String.valueOf(file.getSize()));//获得文件大小
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new java.util.HashMap<>();
        String aa = "cate_93148af8555f4ec49ca1a544bd0c46c0_10544612";
        //aa = new String(aa.getBytes("UTF-8"), "GBK");
        try {
            ApplyFileUploadLeaseResponse result = client.applyFileUploadLeaseWithOptions(
                    categoryId,//不同类目:政策,活动,将类目存入数据库
                    "llm-tt1zzffjohw0mige",//工作空间
                    applyFileUploadLeaseRequest,
                    headers,
                    runtime
            );
            ApplyFileUploadLeaseResponseBody.ApplyFileUploadLeaseResponseBodyData data = result.getBody().getData();
            FileUploadLeaseId = data.fileUploadLeaseId;//租约唯一 ID，后续调用 AddFile 接口时，需要使用该参数。
            System.out.println("FileUploadLeaseId:" + FileUploadLeaseId);
            FileUploadUrl = result.getBody().getData().getParam().url;//文档的上传 URL 地址。
            System.out.println("FileUploadUrl:" + FileUploadUrl);
            System.out.println(data.getParam().getHeaders());
            Map<String, String> headers1 = (Map<String, String>) data.getParam().getHeaders();
            Xbailianextra = headers1.get("X-bailian-extra");
            ContentType = headers1.get("Content-Type");
            System.out.println("申请文档上传租约");
            UploadFile(file);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return fileId;
    }
    public void UploadFile(MultipartFile file) throws Exception {
        String preSignedUrlOrHttpUrl = FileUploadUrl;
        uploadFile(preSignedUrlOrHttpUrl, file);
        AddFile();
    }
    public static void uploadFile(String preSignedUrl, MultipartFile file) {
        HttpURLConnection connection = null;
        try {
            // 创建URL对象
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法用于文档上传，需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
            connection.setRequestMethod("PUT");
            // 允许向connection输出，因为这个连接是用于上传文档的
            connection.setDoOutput(true);
            connection.setRequestProperty("X-bailian-extra", Xbailianextra);
            connection.setRequestProperty("Content-Type", ContentType);
            // 上传文件内容
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 InputStream fileInputStream = file.getInputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // 检查响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("文件上传成功");
            } else {
                System.out.println("文件上传失败，响应码：" + responseCode);
                throw new RuntimeException("文件上传失败，响应码：" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    //第三步:添加文档
    public void AddFile() throws Exception {
        com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest()
                .setLeaseId(FileUploadLeaseId)
                .setParser("DASHSCOPE_DOCMIND")
                .setCategoryId(cate);//类目cate_a191a5db23f5466ea126af3811985f87_10544612
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new java.util.HashMap<>();
        try {
            // 复制代码运行请自行打印 API 的返回值
            AddFileResponse addFileResponse = client.addFileWithOptions("llm-tt1zzffjohw0mige", addFileRequest, headers, runtime);
            fileId = addFileResponse.getBody().getData().fileId;
            System.out.println("fileId:" + fileId);
            System.out.println("添加文档到数据管理");
            SubmitIndexAddDocumentsJob();
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
    public void SubmitIndexAddDocumentsJob() throws Exception {
        com.aliyun.bailian20231229.models.SubmitIndexAddDocumentsJobRequest submitIndexAddDocumentsJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexAddDocumentsJobRequest()
                .setIndexId("ffxh57kcvi")//知识库id
                .setSourceType("DATA_CENTER_FILE")
                .setDocumentIds(java.util.Arrays.asList(
                        fileId
                ));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new java.util.HashMap<>();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.submitIndexAddDocumentsJobWithOptions("llm-tt1zzffjohw0mige", submitIndexAddDocumentsJobRequest, headers, runtime);
            System.out.println("提交知识库");
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
    /**
     * 删除文件
     * @param id
     */
    public void DeleteFile(String id) {
        try {
            client = config.createClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.deleteFileWithOptions(id, "llm-tt1zzffjohw0mige", headers, runtime);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
    public void DeleteIndexDocument(List<String> ids) {
        try {
            client = config.createClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        com.aliyun.bailian20231229.models.DeleteIndexDocumentRequest deleteIndexDocumentRequest = new com.aliyun.bailian20231229.models.DeleteIndexDocumentRequest()
                .setIndexId("ffxh57kcvi")
                .setDocumentIds(ids);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.deleteIndexDocumentWithOptions("llm-tt1zzffjohw0mige", deleteIndexDocumentRequest, headers, runtime);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}